<template>
  <div>
    <!-- 导航 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <!-- 面板 -->
      <el-row :gutter="20">
        <el-col :span="4">
          <el-button type="primary" @click="addBox = true">添加角色</el-button>
        </el-col>
      </el-row>
      <!-- 表格 -->
      <el-table :data="rolesList" border stripe>
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row :class="[i1==0?'batop':'' ,'bdbattom','vcenter']" v-for="item,i1 in scope.row.children" :key="item.id">
              <!-- 一级权限 -->
              <el-col :span='5'>
                <el-tag @close="removeRight(scope.row,item.id)" closable>{{item.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 二级和三级权限 -->
              <el-col :span='19'>
                <el-row :class="[i2==0?'':'batop'  ,'vcenter']" v-for="item2 ,i2 in item.children" :key="item2.id">
                  <el-col :span='6'>
                    <el-tag type="success" @close="removeRight(scope.row,item2.id)" closable>{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span='18'>
                    <el-tag v-for="item3 in item2.children" @close="removeRight(scope.row,item3.id)" :key="item3.id" type="warning" closable>{{item3.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type='index' label="序号"></el-table-column>
        <el-table-column prop="roleName" label="角色名称"></el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
          <el-button size="mini" type="primary" icon='el-icon-edit' @click="updateList(scope.row.id)">编辑</el-button>
          <el-button size="mini" type="danger" icon='el-icon-delete' @click="getDel(scope.row.id)">删除</el-button>
          <el-tooltip class="item" effect="dark" content="分配权限" placement="top">
            <el-button size="mini" type="warning" icon='el-icon-setting' @click="showRightsBox(scope.row)" >分配权限</el-button>
          </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </el-card>


    <!-- 添加用户弹出框 -->
    <el-dialog title="新增角色" :visible.sync="addBox">
      <el-form :model="addForm">
      <el-form-item   prop="roleName">
        <label for="">角色名称</label>
        <el-input  v-model="addForm.roleName" ></el-input>
      </el-form-item>
      <el-form-item   prop="roleName">
        <label for="">角色描述</label>
        <el-input   v-model="addForm.roleDesc" ></el-input>
      </el-form-item>
      </el-form>
       <div slot="footer" class="dialog-footer">
          <el-button @click="addBox=false">取 消</el-button>
          <el-button type="primary" @click="getRolesrAdd">确 定</el-button>
       </div>
    </el-dialog>

    <!-- 添加用户弹出框 -->
    <el-dialog title="修改角色" :visible.sync="updateBox">
      <el-form :model="updateForm">
      <el-form-item   prop="roleName">
        <label for="">角色名称</label>
        <el-input  v-model="updateForm.roleName" ></el-input>
      </el-form-item>
      <el-form-item   prop="roleName">
        <label for="">角色描述</label>
        <el-input   v-model="updateForm.roleDesc" ></el-input>
      </el-form-item>
      </el-form>
       <div slot="footer" class="dialog-footer">
          <el-button @click="updateBox=false">取 消</el-button>
          <el-button type="primary" @click="getRolesrUpdate">确 定</el-button>
       </div>
    </el-dialog>


    <!-- 分配权限对话框 -->
    <el-dialog title="权限分配" :visible.sync="rightBox">
      <el-tree ref="mytree" @close='closeRightBox' :data="rightsList" show-checkbox node-key="id" 
      :default-checked-keys="defKeys" default-expand-all :props="defaultProps">
      </el-tree>
       <div slot="footer" class="dialog-footer">
          <el-button @click="rightBox=false">取 消</el-button>
          <el-button type="primary" @click="setRights">确 定</el-button>
       </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      //默认关闭弹出框
      addBox:false,
      updateBox:false,
      rightBox:false,
      rolesList: [],
      addForm:{roleName:'',roleDesc:''},
      updateForm:{},
      //当前角色id
      roleId:'',
      rightsList:[],
      defKeys:[],//默认选择的节点
      defaultProps: {
          children: 'children',
          label: 'authName'
        }
    }
  },
  created() {
    this.getRolesList(); // ajax 获取用户数据
  },
  methods: {
    async getRolesList() {
      let ret = await this.$http.get('roles');
      if (ret.meta.status !== 200) {
        return this.$message.error(ret.meta.msg);
      }
      this.rolesList = ret.data;
    },
    // 显示分配权限
    async showRightsBox(row){
      this.rightBox=true;
      this.roleId=row.id;
      this.defKeys=[]
      let ret=await this.$http.get('rights/tree');
      this.rightsList=ret.data;
      this.getLeafKeys(row,this.defKeys);
      // console.log(row);
    },
    //通过递归形式,找三级保存到defkeys数组中
    getLeafKeys(node,arr){
      if(!node.children){
        return arr.push(node.id)
      }
      node.children.forEach(item => this.getLeafKeys(item,arr));
    },
    closeRightBox(){
      this.defKeys=[]
    },
    async setRights(){
      let a=this.$refs.mytree.getCheckedKeys()
      let b=this.$refs.mytree.getHalfCheckedKeys()
      let c=[...a,...b]
      let rids=c.join(',');
      // console.log('权限ids=',rids);
      let ret=await this.$http.post(`roles/${this.roleId}/rights`,{rids})
      this.boxMsg(ret.meta.status,200,ret.meta.msg)
      this.getRolesList();
      this.rightBox=false;
    },
    //添加
    async getRolesrAdd(){
      let ret=await this.$http.post('roles',this.addForm);
      //成功失败提示
      this.boxMsg(ret.meta.status,201,ret.meta.msg);
      this.getRolesList();
      this.addBox=false;
    },
    // 查询修改数据
    async updateList(id){
      this.updateBox=true;
      let ret= await this.$http.get(`roles/${id}`);
      this.updateForm=ret.data;
    },
    // 修改
    async getRolesrUpdate(){
      let ret= await this.$http.put(`roles/${this.updateForm.roleId}`,this.updateForm);
      //成功失败提示
      this.boxMsg(ret.meta.status,200,ret.meta.msg);
      this.getRolesList()
      this.updateBox=false;
    },
    // 删除
    async getDel(id){
      let ok=await this.$confirm('此操作将永久删除, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err=>err);
        if(ok!='confirm'){
          return this.$message.info('你取消了删除')
        }
      let ret =await this.$http.delete(`roles/${id}`)
      this.boxMsg(ret.meta.status,200,ret.meta.msg);
      this.getRolesList();
    },
    async removeRight(row,rid){
       let ok=await this.$confirm('此操作将永久删除, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err=>err);
        if(ok!='confirm'){
          return this.$message.info('你取消了删除')
        }
      let ret=await this.$http.delete(`roles/${row.id}/rights/${rid}`)
      //成功失败提示
      this.boxMsg(ret.meta.status,200,ret.meta.msg);
        //更新当前人的权限
        row.children=ret.data;
      // console.log(ret);
    },
    //成功失败提示
    boxMsg(a,b,msg){
      if(a !=b){
        return this.$message.error(msg);
      }
      // 成功提示
      this.$message({
           message: msg,
          type: 'success'
        });
    }
  }
}
</script>

<style lang="less" scoped>
.el-tag{
  margin: 7px;
}
.batop{
  border-top: 1px solid #eee;
}
.bdbattom{
  border-bottom: solid 1px #eee;

}
.vcenter{
  display: flex;
  align-items: center;
}
</style>


